<template>
  <!-- header部分 -->
    <header>
        <p>商家信息</p>
    </header>


  <!-- 商家logo部分 -->
    <div class="business-logo">
        <img :src=business.businessImg>
    </div>

  <!-- 商家信息部分 -->
    <div class="business-info">
        <h1>{{business.businessName}}</h1>
        <p>&#165;{{business.starPrice}}起送 &#165;{{business.deliveryPrice}}配送</p>
        <p>{{business.businessExplain}}</p>
    </div>

  <!-- 食品列表部分 -->
    <ul class="food">
        <template v-for="item in foodList">
            <li>
                <FoodItem
                        :food="item"
                        :businessId="business.businessId"
                        :quantity="getFoodQuantity(item)"
                        @updateCart="updateCart"

                />
            </li>
        </template>
    </ul>
<!--    购物车-->
  <Cart
          :cart="cart"
          :deliveryPrice="business.deliveryPrice"
          :businessId="businessId"
  />
</template>

<script setup>
import FoodItem from "../components/FoodItem.vue";
import Cart from "../components/Cart.vue";
import {useCartStore} from "../store/cart.js";
import {useRoute} from "vue-router";
import {computed,onMounted, reactive, ref} from "vue";
import {
    creatCartAPI,
    getBusinessByBusinessIdAPI,
    getFoodsByBusinessIdAPI,
    listCartAPI, removeCartItemAPI,
    updateCartAPI
} from "../api/api.js";
import {getSessionStorage} from "../common.js";
const cartStore = useCartStore()
const  business = ref({})
const foodList = reactive([])
//定义购物车列表
const cart = reactive([])
//定义节流阀
const isRequest = ref(false)
const token  = getSessionStorage("user").token
//定义获取购物车的方法
const getCartList = (businessId)=>{
    const data = new FormData()
    data.append("userPhone",getSessionStorage("user").userPhone)
    data.append("businessId",businessId)
     listCartAPI(token,data).then(res=>{
        cart.splice(0,cart.length)
        cart.push(...res.data.data)
         //加入状态管理
        cartStore.setCartInfo({
            businessId:businessId,
            cartData:res.data.data
        })
    })
}

//定义计算属性
const getFoodQuantity = computed(() => (foodItem) => {
    const quantity = ref(0)
    const index = cart.findIndex(cartItem => foodItem.foodId === cartItem.food.foodId)
    if (index === -1){
        return quantity.value;
    }else {
        quantity.value = cart[index].quantity
        return quantity.value
    }
})

const route = useRoute()
const businessId = route.params.businessId
onMounted(async ()=>{
     //获取商家信息
    await getBusinessByBusinessIdAPI(businessId).then(res=>{
         business.value = res.data.data
    })
    //获取商家商品
    await getFoodsByBusinessIdAPI(businessId).then(res=>{
        foodList.splice(0,foodList.length)
        foodList.push(...res.data.data)
    })
    //获取用户在该商家下的购物车
    await getCartList(businessId)


})

//更新购物车：
//1、如果 更新前是0，更新后大于0，则创建购物车
//2、如果 更新前小于更新后，则增加
//3、如果 更新前大于更新后，则减少
const updateCart = async (cartData)=>{
    const finalQuantity = cartData.formData.get("quantity")
    if (isRequest.value){
        console.log("服务器繁忙")
    }else {
        isRequest.value = true;
        if (cartData.originalQuantity === 0 && finalQuantity>0){
            // console.log("新建")
            await creatCartAPI(token,cartData.formData).then(res=>console.log(res.data.msg)).catch(e=>console.log(e))
        }else if (cartData.originalQuantity<finalQuantity){
            // console.log("增加")
            await updateCartAPI(token,cartData.formData).then(res=>console.log(res.data.msg)).catch(e=>console.log(e))
        }else {
            await removeCartItemAPI(token,cartData.formData).then(res=>console.log(res.data.msg)).catch(e=>console.log(e))
            // console.log("减少")
        }
        //重新更新数据
        await getCartList(businessId)
        isRequest.value = false
    }

}
</script>

<style scoped>
/****************** header部分 ******************/
header{
    width: 100%;
    height: 12vw;
    background-color: #0097FF;
    color: #fff;
    font-size: 4.8vw;

    position: fixed;
    left: 0;
    top: 0;
    z-index: 1000;

    display: flex;
    justify-content: center;
    align-items: center;
}
/****************** 商家logo部分 ******************/
.business-logo{
    width: 100%;
    height: 35vw;
    /*使用上外边距避开header部分*/
    margin-top: 12vw;

    display: flex;
    justify-content: center;
    align-items: center;
}
.business-logo img{
    width: 40vw;
    height: 30vw;
    border-radius: 5px;
}
/****************** 商家信息部分 ******************/
.business-info{
    width: 100%;
    height: 20vw;

    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.business-info h1{
    font-size: 5vw;
    margin-bottom: 0;
}
.business-info p{
    font-size: 3vw;
    color: #666;
    margin-top: 1vw;
    margin-bottom: 0;
}
.food{
    width: 100%;
    /*使用下外边距避开footer部分*/
    margin-bottom: 14vw;
}
.food li{
    width: 100%;
    box-sizing: border-box;
    padding: 2.5vw;
    user-select: none;

    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>